<?php

class AuthController extends Controller
{
	public $layout = false;
	public function actionLogin()
	{
		$username = Yii::app()->request->getPost('username', null);
		$password = Yii::app()->request->getPost('password', null);
		$verifyCode  = Yii::app()->request->getPost('verifyCode', null);
		if(!isset($_SESSION['login_attempts'])) $_SESSION['login_attempts'] = 0;
		if($_SESSION['login_attempts'] > 5){
			echo 'Your access has been temporarily restricted due to too many failed login attempts!'; exit;
		}
		//do login
		if(Yii::app()->request->isPostRequest){
			try{
				//check captcha
				$objCaptcha=Yii::app()->getController()->createAction("captcha"); 
				if(!empty($verifyCode) && $verifyCode === $objCaptcha->verifyCode){
					$identity=new AdminIdentity($username,$password);
					if($identity->authenticate()){
						//login successfully
						Yii::app()->admin->login($identity);
						unset($_SESSION['login_attempts']);
						$this->redirect(Yii::app()->request->baseUrl.'/admincp');
						exit;
					}
					else{
						//wrong credentials 
						$_SESSION['login_attempts']++;
						Yii::app()->admin->setFlash('error', Yii::t('AdmincpModule.admincp', 'Wrong username or password'));
					}
				} else {
					//wrong captcha
					Yii::app()->admin->setFlash('error', Yii::t('AdmincpModule.admincp', 'Wrong security captcha'));
				}
			} catch (Exception $ex){
				Yii::app()->admin->setFlash('error', Yii::t('AdmincpModule.admincp', $ex->getMessage()));
			}
			//regenerate captcha
			$objCaptcha->getVerifyCode(true);
			$this->refresh();
		}
		//render layout
		$this->render('login');
	}
	
	public function actionLogout(){
		Yii::app()->admin->logout();
		$this->redirect(Yii::app()->request->baseUrl.'/admincp');
	}
	
	public function actionReset(){
		$username = Yii::app()->request->getPost('username', null);
		$verifyCode  = Yii::app()->request->getPost('verifyCode', null);
		if(Yii::app()->request->isPostRequest){
			//check captcha
			$objCaptcha=Yii::app()->getController()->createAction("captcha"); 
			if(!empty($verifyCode) && $verifyCode === $objCaptcha->verifyCode){
				/* get user information */
				$user = Users::getInstance()->getByUsername($username);
				if(!empty($user)){
					/* create identity code */
					echo $strToken = Users::getInstance()->getToken($user); die;
				}
				else{
					
				}
			} else {
				Yii::app()->admin->setFlash('error', Yii::t('AdmincpModule.admincp', 'Wrong security captcha'));
				//regenerate captcha
				$objCaptcha->getVerifyCode(true);
			}
		}
		$this->render('reset');
	}
	
	public function actions(){
		return array(
			// captcha action renders the CAPTCHA image displayed on the user registration page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF
			)
		);
	}
}